<?php

class User extends MX_Controller {
	
	function index()
	{
	//	$data['main_content'] = 'login_form';
	//	$this->load->view('includes/template', $data);	
		redirect('site');
	}
	
	function validate_user()
	{
		$this->load->model('register_model');
		$query = $this->register_model->validate();
	
		if($query) // if the user's credentials validated...
		{
			$data = array(
					'is_logged_in' => true,
					'username' => $this->input->post('username'),
					'password' => $this->input->post('password'),
					'userid'   => $query['userId']
			);
			$this->session->set_userdata($data);
			redirect('site');
		}
		else // incorrect username or password
		{
			$this->index();
		}
	}	
	
	function signup_index()
	{
		$data['main_content'] = 'signup_form_index';
		$this->load->view('includes/template', $data);
	}
	
	function validate_register(){
		$this->load->model('register_model');
		$reg = $this->register_model->register();
		
	}
	

	function create_user()
	{
		$this->load->library('form_validation');
	
		// field name, error message, validation rules
		$this->form_validation->set_rules('firstName', 'FirstName', 'trim|required');
		$this->form_validation->set_rules('lastName', 'Last Name', 'trim|required');
		$this->form_validation->set_rules('inputEmail', 'Email Address', 'trim|required|valid_email');
	
	
		if($this->form_validation->run() == FALSE)
		{
			$this->load->view('signup_form_index');
		}
		else
		{
			$this->load->model('register_model');
				
			if($query = $this->register_model->add_user()){
				$data['main_content'] = 'signup_successful';
				$this->load->view('includes/template', $data);
			} else {
				$this->load->view('signup_form_index');
			}
		}
	
	}
	
	function logout()
	{
		$this->session->unset_userdata('username');
		$this->session->unset_userdata('is_logged_in');
		$this->session->sess_destroy();
		$this->index();
	}	
	
	function is_logged_in()
	{
		$is_logged_in = $this->session->userdata('is_logged_in');
		if(!isset($is_logged_in) || $is_logged_in != true)
		{
			echo 'You don\'t have permission to access this page. <a href="../login">Login</a>';	
			die();		
			//$this->load->view('login_form');
		}		
	}
}